package tools.emboss;

import java.io.BufferedReader;
import java.io.IOException;


public class embossParser {

	private BufferedReader reader;
	private boolean hasmoreseq= true;
	private embossAlignment curralign= null;

	public embossParser(BufferedReader reader) throws IOException, Exception {
		this.reader= reader;
		readNext();
	}
	
	/* (non-Javadoc)
	 * @see java.util.Iterator#hasNext()
	 */
	public boolean hasNext() {
		return hasmoreseq;
	}

	/* (non-Javadoc)
	 * @see java.util.Iterator#next()
	 */
	public embossAlignment next() {
		try {
			return nextAlignment();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * @deprecated
	 * @return
	 */
	public boolean hasMoreAlignments() {
		return hasmoreseq;
	}
	
	/**
	 * @deprecated
	 * @return
	 * @throws IOException
	 * @throws BioException
	 */
	public embossAlignment nextAlignment() throws IOException, Exception {
		if (hasmoreseq == false) 
			throw new Exception("No more sequences");
		embossAlignment tmp= new embossAlignment(curralign);
		readNext();
		
		return tmp;
	}
	
	private void readNext() throws IOException, Exception {
		String s= reader.readLine();
		if (s==null) {
			hasmoreseq= false;
		}
		else {
			String[] l= s.split("\t");
			if (l.length != 10) {
				throw new Exception("Invalid line: "+s);
			}
			
			embossAlignment align= new embossAlignment();
			align.setQname(l[0]);
			align.setTname(l[1]);
			align.setMatrix(l[2]);
			align.setGap_penalty(Double.parseDouble(l[3]));
			align.setGap_extension_penalty(Double.parseDouble(l[4]));
			align.setAlignment_length(Integer.parseInt(l[5]));
			align.setIdentity(Integer.parseInt(l[6]));
			align.setSimilarity(Integer.parseInt(l[7]));
			align.setGaps(Integer.parseInt(l[8]));
			align.setScore(Double.parseDouble(l[9]));
			
			curralign = align;
			hasmoreseq= true;
		}
	}
}
